/**
 *
 */
package com.zhengtoon.mctoon.conv.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.qitoon.framework.core.exception.BusinessException;
import com.zhengtoon.mctoon.conv.bean.CityItem;
import com.zhengtoon.mctoon.conv.bean.ConfigDict;
import com.zhengtoon.mctoon.conv.bean.ConvAttachment;
import com.zhengtoon.mctoon.conv.bean.ConvHandleRecord;
import com.zhengtoon.mctoon.conv.bean.ConvMsgRecord;
import com.zhengtoon.mctoon.conv.bean.ConvPhotoInfo;
import com.zhengtoon.mctoon.conv.bean.ConvRemindRecord;
import com.zhengtoon.mctoon.conv.bean.ConvSubject;
import com.zhengtoon.mctoon.conv.bean.msg.MessageAppRequest;
import com.zhengtoon.mctoon.conv.bean.session.OrgSessionInfo;
import com.zhengtoon.mctoon.conv.dao.ConvAttachmentMapper;
import com.zhengtoon.mctoon.conv.dao.ConvCommentMapper;
import com.zhengtoon.mctoon.conv.dao.ConvHandleRecordMapper;
import com.zhengtoon.mctoon.conv.dao.ConvMsgRecordMapper;
import com.zhengtoon.mctoon.conv.dao.ConvPhotoInfoMapper;
import com.zhengtoon.mctoon.conv.dao.ConvPraiseInfoMapper;
import com.zhengtoon.mctoon.conv.dao.ConvRemindRecordMapper;
import com.zhengtoon.mctoon.conv.dao.ConvSubjectMapper;
import com.zhengtoon.mctoon.conv.dto.AddAuditDto;
import com.zhengtoon.mctoon.conv.dto.AddReportDto;
import com.zhengtoon.mctoon.conv.dto.AuditConfigDto;
import com.zhengtoon.mctoon.conv.dto.ConvHandleResult;
import com.zhengtoon.mctoon.conv.dto.PendingAuditDetailDto;
import com.zhengtoon.mctoon.conv.dto.PendingAuditListResultItemDto;
import com.zhengtoon.mctoon.conv.dto.PendingReportListResultItemDto;
import com.zhengtoon.mctoon.conv.dto.PublishedConvDetailDto;
import com.zhengtoon.mctoon.conv.dto.PublishedConvListResultItemDto;
import com.zhengtoon.mctoon.conv.dto.ReportDetailDto;
import com.zhengtoon.mctoon.conv.dto.RequestReleaseDto;
import com.zhengtoon.mctoon.conv.dto.ResultConvPhotoDto;
import com.zhengtoon.mctoon.conv.dto.ResultConvPhotoInfoDto;
import com.zhengtoon.mctoon.conv.dto.ResultPhotoDto;
import com.zhengtoon.mctoon.conv.dto.ResultPraisConvPhotoDto;
import com.zhengtoon.mctoon.conv.dto.ResultProblemHandDto;
import com.zhengtoon.mctoon.conv.dto.mybatis.Page;
import com.zhengtoon.mctoon.conv.dto.param.ConvLetterParam;
import com.zhengtoon.mctoon.conv.dto.response.SubjectConvPhotoDto;
import com.zhengtoon.mctoon.conv.dto.sdzc.ZfhfLetterResultDto;
import com.zhengtoon.mctoon.conv.exception.ConvPhotoExceptionCode;
import com.zhengtoon.mctoon.conv.service.sdzc.LetterService;
import com.zhengtoon.mctoon.conv.service.sdzc.ReplyService;
import com.zhengtoon.mctoon.conv.utils.AppConstant;
import com.zhengtoon.mctoon.conv.utils.CertficateUtils;
import com.zhengtoon.mctoon.conv.utils.CityIntegralUtils;
import com.zhengtoon.mctoon.conv.utils.ConfigDictUtils;
import com.zhengtoon.mctoon.conv.utils.DateFormatAppUtils;
import com.zhengtoon.mctoon.conv.utils.IMUtils;
import com.zhengtoon.mctoon.conv.utils.MsgFormatUtils;
import com.zhengtoon.mctoon.conv.utils.SessionInfo;
import com.zhengtoon.mctoon.conv.utils.SysConfig;
import com.zhengtoon.mctoon.conv.utils.ToonUtils;

/**
 * 随手拍 impl实现
 *
 * @author 赵康峰
 * @since 2017-05-26
 * Copyright: Copyright (c) 2017
 * Company:北京政务通科技有限公司
 */
@Service
public class ConvPhotoInfoServiceImpl implements ConvPhotoInfoService {

    private static Logger log = LoggerFactory.getLogger(ConvPhotoInfoServiceImpl.class);

    @Autowired
    private ReplyService replyService;

    @Autowired
    private LetterService letterService;

    @Autowired
    private ConvPhotoInfoMapper convPhotoInfoMapper;

    @Autowired
    private ConvAttachmentMapper convAttachmentMapper;

    @Autowired
    private ConvPraiseInfoMapper convPraiseInfoMapper;

    @Autowired
    private ConvCommentMapper convCommentMapper;

    @Autowired
    private ConvHandleRecordMapper convHandleRecordMapper;

    @Autowired
    private ConvRemindRecordMapper convRemindRecordMapper;

    @Autowired
    private ConvMsgRecordMapper convMsgRecordMapper;

    @Autowired
    private ConvSubjectMapper convSubjectMapper;

    // 发消息http地址
    private static String CONV_HOST = SysConfig.getPropertyValue("config.convphoto_host");

    // 上传图片限制
    private static String UPLOAD_PHOTO_NUM_LIMIT = SysConfig.getPropertyValue("config.upload_photo_num_limit");


    @Override
    @Transactional
    public int addPhotos(RequestReleaseDto releaseDto, SessionInfo sessionInfo) throws BusinessException {

        try {
            int result;
            //获取手机号
            String mobile = ToonUtils.getMobileByUserId(sessionInfo.getUserId());
            boolean flag = CertficateUtils.getCertApply(sessionInfo.getUserId());
            ConvPhotoInfo convPhotoInfo = new ConvPhotoInfo();
            convPhotoInfo.setContent(releaseDto.getContent());
            convPhotoInfo.setPlace(releaseDto.getLocation());
            convPhotoInfo.setUserId(sessionInfo.getUserId());
            convPhotoInfo.setAuditCode(AppConstant.CONV_AUDIT_CODE);
            convPhotoInfo.setAudit(AppConstant.CONV_AUDIT);
            convPhotoInfo.setCreateTime(new Date().getTime());
            convPhotoInfo.setUpdateTime(new Date().getTime());
            convPhotoInfo.setMobile(mobile);
            convPhotoInfo.setSubjectId(releaseDto.getSubjectId());
            //是否实名认证1:是2：否
            if (flag) {
                convPhotoInfo.setAuditCert(1);
            } else {
                convPhotoInfo.setAuditCert(2);
            }
            //插入随手拍记录
            convPhotoInfoMapper.addPhotos(convPhotoInfo);
            handleUploadNumLimit(releaseDto.getPhotos());
            //插入附件
            List<ConvAttachment> attachments = new ArrayList<>();
            for (ConvAttachment attachment : releaseDto.getPhotos()) {
                attachment.setConvId(convPhotoInfo.getConvId());
                attachment.setCreateTime(new Date().getTime());
                attachment.setUpdateTime(new Date().getTime());
                attachments.add(attachment);
            }
            result = convAttachmentMapper.insertList(attachments);
            return result;
        } catch (Exception e) {
            log.error("随手拍记录数据提交错误", e);
            throw new BusinessException(ConvPhotoExceptionCode.ADDCONV_IS_FAIL);
        }
    }

    @Override
    @Transactional
    public int updatePhotos(RequestReleaseDto releaseDto, SessionInfo sessionInfo) throws BusinessException {
        try {
            int result;
            boolean flag = CertficateUtils.getCertApply(sessionInfo.getUserId());
            ConvPhotoInfo convPhotoInfo = new ConvPhotoInfo();
            convPhotoInfo.setContent(releaseDto.getContent());
            convPhotoInfo.setPlace(releaseDto.getLocation());
            convPhotoInfo.setUserId(sessionInfo.getUserId());
            convPhotoInfo.setAuditCode(AppConstant.CONV_AUDIT_CODE);
            convPhotoInfo.setAudit(AppConstant.CONV_AUDIT);
            convPhotoInfo.setUpdateTime(new Date().getTime());
            //是否实名认证1:是2：否
            if (flag) {
                convPhotoInfo.setAuditCert(1);
            } else {
                convPhotoInfo.setAuditCert(2);
            }
            ConvPhotoInfo convPhotoInfo1 = convPhotoInfoMapper.queryConvDetailById(Long.valueOf(releaseDto.getId()));

            if (convPhotoInfo1.getAuditCode() == 1) {
                return -1;
            }
            if (convPhotoInfo1.getAuditCode() == 3) {
                return -2;
            }
            //删除上次提交的附件信息
            convAttachmentMapper.deleteAttachments(Long.valueOf(releaseDto.getId()));
            //修改随手拍记录
            convPhotoInfo.setConvId(Long.valueOf(releaseDto.getId()));
            convPhotoInfoMapper.updatePhotos(convPhotoInfo);

            handleUploadNumLimit(releaseDto.getPhotos());

            List<ConvAttachment> attachments = new ArrayList<>();
            for (ConvAttachment attachment : releaseDto.getPhotos()) {
                attachment.setConvId(convPhotoInfo.getConvId());
                attachment.setCreateTime(new Date().getTime());
                attachment.setUpdateTime(new Date().getTime());
                attachments.add(attachment);
            }
            result = convAttachmentMapper.insertList(attachments);
            //处理消息覆盖(打标签)
            getLabelMsg(Long.valueOf(releaseDto.getId()));
            return result;
        } catch (Exception e) {
            log.error("随手拍记录数据提交错误", e);
            throw new BusinessException(ConvPhotoExceptionCode.ADDCONV_IS_FAIL);
        }

    }

    /**
     * 检查上传图片是否超过限制
     *
     * @param photos
     * @author 144637
     */
    private void handleUploadNumLimit(List<ConvAttachment> photos) {
        Integer photoNumLimit = AppConstant.CONV_PHOTO_NUM_LIMIT;
        if (StringUtils.isNotBlank(UPLOAD_PHOTO_NUM_LIMIT)) {
            photoNumLimit = Integer.valueOf(UPLOAD_PHOTO_NUM_LIMIT);
        }
        if (photos.size() > photoNumLimit) {
            throw new BusinessException(ConvPhotoExceptionCode.UPLOAD_PHOTO_TOO_MANY);
        }
    }


    @Override
    public Integer updShowFlag(Long convId, Integer showFlag) {
        int i = convPhotoInfoMapper.updShowFlag(convId, showFlag);
        return i;
    }


    @Override
    public List<ResultConvPhotoDto> queryPhotoList(String pageNum, String pageSize, String userId) {

        Integer num = Integer.valueOf(pageNum);
        Integer size = Integer.valueOf(pageSize);
        List<ConvPhotoInfo> list = convPhotoInfoMapper.getPhotoList((num - 1) * size, size, Long.valueOf(userId));
        List<ResultConvPhotoDto> resultConvPhotoDtoDtoList = new ArrayList<>();
        for (ConvPhotoInfo convPhotoInfo : list) {
            try {
                ResultConvPhotoDto resultConvPhotoDto = getConvInfoDto(userId, convPhotoInfo);
                resultConvPhotoDtoDtoList.add(resultConvPhotoDto);
            } catch (Exception e) {
                log.error("我的随手拍列表错误：" + e);
            }
        }
        return resultConvPhotoDtoDtoList;
    }

    @Override
    public ResultConvPhotoInfoDto queryPhotoDetailById(String id, String userId) {

        ConvPhotoInfo convPhotoInfo = convPhotoInfoMapper.getPhotoInfo(Long.valueOf(id));
        ResultConvPhotoInfoDto resultConvPhotoInfoDto = new ResultConvPhotoInfoDto();
        resultConvPhotoInfoDto.setContent(convPhotoInfo.getContent());
        resultConvPhotoInfoDto.setCreateTime(DateFormatAppUtils.formatDateTime(convPhotoInfo.getCreateTime()));
        resultConvPhotoInfoDto.setLocation(convPhotoInfo.getPlace());
        resultConvPhotoInfoDto.setPhotos(getPhotos(convPhotoInfo.getConvId()));
        resultConvPhotoInfoDto.setAuditCode(String.valueOf(convPhotoInfo.getAuditCode()));
        //判断此记录是否用户本人记录
        if (convPhotoInfo.getUserId().equals(userId)) {
            resultConvPhotoInfoDto.setAuthor(true);
        } else {
            resultConvPhotoInfoDto.setAuthor(false);
        }
        if (convPhotoInfo.getAuditCode() == 3) {
            resultConvPhotoInfoDto.setConvType(String.valueOf(convPhotoInfo.getTypeCode()));
            //当随手拍类型为最美北京/社会警示，获取点赞总数，评论总数，是否赞过
            if (convPhotoInfo.getTypeCode() == 1 || convPhotoInfo.getTypeCode() == 3) {
                //点赞总数
                resultConvPhotoInfoDto.setPraiseCount(getPraiseCount(convPhotoInfo.getConvId()));
                //评论总数
                resultConvPhotoInfoDto.setCommentCount(getCommentCount(convPhotoInfo.getConvId(), Long.valueOf(userId)));
                //是否赞过
                resultConvPhotoInfoDto.setPraised(isPraise(convPhotoInfo.getConvId(), userId));
            }
            //当随手拍类型为举报处理时，获取处理记录列表
            if (convPhotoInfo.getTypeCode() == 2) {
                resultConvPhotoInfoDto.setDealStatus(String.valueOf(convPhotoInfo.getIsOver()));
                resultConvPhotoInfoDto.setFeedback(String.valueOf(convPhotoInfo.getFeedback()));
                List<ConvHandleRecord> list = convHandleRecordMapper.getDealProcess(convPhotoInfo.getConvId());
                List<ConvHandleResult> results = new ArrayList<>();
                for (ConvHandleRecord convHandleRecord : list) {
                    ConvHandleResult convHandleResult = new ConvHandleResult();
                    convHandleResult.setCreateTime(DateFormatAppUtils.formatDateTime(convHandleRecord.getCreateTime()));
                    convHandleResult.setHandleChannel(convHandleRecord.getHandleChannel());
                    convHandleResult.setHandleMode(convHandleRecord.getHandleMode());
                    convHandleResult.setHandleResult(convHandleRecord.getHandleResult());
                    results.add(convHandleResult);
                }
                resultConvPhotoInfoDto.setDealProcess(results);
            }
        }
        //如果有新评论则重置新提醒记录
        if (querCommenting(convPhotoInfo.getConvId())) {

            convRemindRecordMapper.updateRemindReset(convPhotoInfo.getConvId(), new Date().getTime());
        }
        // 查询专题名称
        if (StringUtils.isNotBlank(convPhotoInfo.getSubjectId())) {
            ConvSubject subjectEntity = convSubjectMapper.querySubjectDetail(Long.valueOf(convPhotoInfo.getSubjectId()));
            if (subjectEntity != null) {
                resultConvPhotoInfoDto.setSubjectId(convPhotoInfo.getSubjectId());
                resultConvPhotoInfoDto.setSubjectName(subjectEntity.getSubjectName());
            }
        }
        return resultConvPhotoInfoDto;
    }

    @Override
    public int updateUserFeedBack(String id, int userFeedBack, String messge) {
        convPhotoInfoMapper.updateUserFeedBack(Long.valueOf(id), userFeedBack, messge, new Date().getTime());
        //处理消息覆盖(打标签)
        getLabelMsg(Long.valueOf(id));
        return 1;
    }


    @Override
    public List<ResultPraisConvPhotoDto> queryPraisPhotoList(String pageNum, String pageSize, String userId, int typeCode) {

        Integer num = Integer.valueOf(pageNum);
        Integer size = Integer.valueOf(pageSize);
        List<ConvPhotoInfo> list = convPhotoInfoMapper.getPraisPhotoList((num - 1) * size, size, typeCode);
        List<ResultPraisConvPhotoDto> resultPraisConvPhotoDtoList = new ArrayList<>();
        for (ConvPhotoInfo convPhotoInfo : list) {
            try {
                ResultPraisConvPhotoDto resultPraisConvPhotoDto = new ResultPraisConvPhotoDto();
                resultPraisConvPhotoDto.setId(String.valueOf(convPhotoInfo.getConvId()));
                resultPraisConvPhotoDto.setTitle(convPhotoInfo.getContent());
                resultPraisConvPhotoDto.setCreateTime(String.valueOf(convPhotoInfo.getCreateTime()));
                //根据随手拍记录id，userId判断是否点赞
                resultPraisConvPhotoDto.setPraised(isPraise(convPhotoInfo.getConvId(), userId));

                //根据随手拍记录id获取点赞数量
                resultPraisConvPhotoDto.setPraiseCount(getPraiseCount(convPhotoInfo.getConvId()));

                //根据随手拍记录表id获取评论总数
                resultPraisConvPhotoDto.setCommentCount(getCommentCount(convPhotoInfo.getConvId(), Long.valueOf(userId)));

                //根据随手拍记录id获取第一张图片
                String photo = convAttachmentMapper.getPhoto(convPhotoInfo.getConvId());
                resultPraisConvPhotoDto.setPhoto(photo);

                //根据随手拍记录id获取图片总数
                int photos = convAttachmentMapper.getPhotosCount(convPhotoInfo.getConvId());
                resultPraisConvPhotoDto.setPhotos(String.valueOf(photos));

                // 查询专题名称
                if (StringUtils.isNotBlank(convPhotoInfo.getSubjectId())) {
                    ConvSubject subjectEntity = convSubjectMapper.querySubjectDetail(Long.valueOf(convPhotoInfo.getSubjectId()));
                    if (subjectEntity != null) {
                        resultPraisConvPhotoDto.setSubjectId(convPhotoInfo.getSubjectId());
                        resultPraisConvPhotoDto.setSubjectName(subjectEntity.getSubjectName());
                    }
                }

                resultPraisConvPhotoDtoList.add(resultPraisConvPhotoDto);
            } catch (Exception e) {
                log.error("查询列表失败", e);
            }
        }
        return resultPraisConvPhotoDtoList;
    }

    /**
     * 处理消息覆盖(打标签)
     *
     * @param convId 随手拍记录表id
     * @return void
     * @author 赵康峰
     */
    private void getLabelMsg(Long convId) {
        //获取消息内容
        ConvMsgRecord convMsgRecord = convMsgRecordMapper.selectMsgRecordByConvId(convId);

        MessageAppRequest messageAppRequest = new MessageAppRequest();
        messageAppRequest.setBizNo(convMsgRecord.getBizNo());
        messageAppRequest.setMsgContent(convMsgRecord.getMsgContent());
        messageAppRequest.setUserId(convMsgRecord.getUserId());
        messageAppRequest.setFinishFlag(AppConstant.MSG_FINISH_FLAG_YES);

        // 消息发送
        IMUtils.sendToonMessage(messageAppRequest);
    }

    /**
     * 通过随手拍记录表id获取点赞总数
     *
     * @param convId 随手拍记录表id
     * @return java.lang.String
     * @author 赵康峰
     */
    private String getPraiseCount(Long convId) {
        return String.valueOf(convPraiseInfoMapper.getPraiseCount(convId));
    }

    /**
     * 通过随手拍记录表id获取评论总数
     *
     * @param convId 随手拍记录表id
     * @return java.lang.String
     * @author 赵康峰
     */
    private String getCommentCount(Long convId, Long userId) {
        int commentCountOther = convCommentMapper.queryCommentCountOther(convId, userId);
        log.debug("获取除自己外的其他人评论数：" + commentCountOther);
        int commentCountUser = convCommentMapper.queryCommentCountUser(convId, userId);
        log.debug("获取自己的评论数：" + commentCountUser);
        return String.valueOf(commentCountOther + commentCountUser);
    }

    /**
     * 通过随手拍记录表id获取处理记录列表
     *
     * @param convId 随手拍记录表id
     * @return java.util.List<com.zhengtoon.mctoon.conv.bean.ConvAttachment>
     * @author 赵康峰
     */
    private List<ResultPhotoDto> getPhotos(Long convId) {
        List<ConvAttachment> list = convAttachmentMapper.getPhotos(convId);
        List<ResultPhotoDto> resultPhotoDtoList = new ArrayList<>();
        for (ConvAttachment convAttachment : list) {
            ResultPhotoDto resultPhotoDto = new ResultPhotoDto();
            resultPhotoDto.setFileUrl(convAttachment.getFileUrl());
            resultPhotoDtoList.add(resultPhotoDto);
        }
        return resultPhotoDtoList;
    }

    /**
     * 通过随手拍记录表id和userid判断是否点赞
     *
     * @param convId 随手拍记录表id
     * @param userId toon用户id
     * @return java.lang.String
     * @author 赵康峰
     */
    private boolean isPraise(Long convId, String userId) {
        int rs = convPraiseInfoMapper.isPraise(convId, userId);
        return rs > 0;
    }

    /**
     * 根据convId获取是否有新提醒
     *
     * @param convId 随手拍记录表id
     * @return java.lang.Boolean
     * @author 赵康峰
     */
    private Boolean querCommenting(Long convId) {
        try {
            ConvRemindRecord convRemindRecord = convRemindRecordMapper.queryRemind(convId);
            if (convRemindRecord == null) {
                return false;
            }
            if (convRemindRecord.getConvType() == 2) {
                return convRemindRecord.getHandleRecordCount() != 0;
            } else if (convRemindRecord.getConvType() == 1 || convRemindRecord.getConvType() == 3) {
                return convRemindRecord.getCommentCount() != 0;
            }
        } catch (Exception e) {
            log.error("跟据convId获取是否有新提醒错误：" + e);
        }
        return false;
    }

    @Override
    public Page queryPendingAuditList(Page page) {

        try {
            // 1. 按条件查询记录,分页,未锁定的记录

            page.setMinuteBefore(DateFormatAppUtils.getTimeBeforeMinutes(AppConstant.LOCK_MINUTES));

            // 查询数据
            List<ConvPhotoInfo> convPhotoInfoList = convPhotoInfoMapper.queryPendingAuditList(page);

            // 查询数据条数
            Integer dataTotal = convPhotoInfoMapper.queryPendingAuditListCount(page);

            //  参数转换,处理
            List<PendingAuditListResultItemDto> resultItmeDtoList = convertToResultItemDto(convPhotoInfoList);


            // 返回参数
            if (dataTotal == null) {
                dataTotal = 0;
            }

            page.setResult(resultItmeDtoList);
            page.setDataTotal(dataTotal);

            return page;
        } catch (Exception e) {
            log.error("查询待审核列表失败", e);
            throw new BusinessException(ConvPhotoExceptionCode.PENDING_AUDIT_ERROR);
        }

    }


    @Override
    public PendingAuditDetailDto queryPendingAuditDetailById(Long convId) {
        try {

            PendingAuditDetailDto detailDto = new PendingAuditDetailDto();

            // 1. 查询随手拍详情
            ConvPhotoInfo photoInfo = convPhotoInfoMapper.queryConvDetailById(convId);

            detailDto.setConvId(photoInfo.getConvId());
            detailDto.setMobile(photoInfo.getMobile());
            detailDto.setCreateTime(DateFormatAppUtils.getFormatDate(photoInfo.getCreateTime()));
            detailDto.setContent(photoInfo.getContent());
            detailDto.setLocation(photoInfo.getPlace());
            detailDto.setUserType(photoInfo.getAuditCert());

            // 查询专题名称
            if (StringUtils.isNotBlank(photoInfo.getSubjectId())) {
                ConvSubject subjectEntity = convSubjectMapper.querySubjectDetail(Long.valueOf(photoInfo.getSubjectId()));
                if (subjectEntity != null) {
                    detailDto.setSubjectId(photoInfo.getSubjectId());
                    detailDto.setSubjectName(subjectEntity.getSubjectName());
                }
            }

            // 2. 查询附件信息

            List<ConvAttachment> convAttachmentList = convAttachmentMapper.getPhotos(convId);

            detailDto.setPhotos(convAttachmentList);

            // 3. 锁定该条记录

            Long lockTime = new Date().getTime();
            convPhotoInfoMapper.lockConvRecord(convId, lockTime);

            return detailDto;
        } catch (Exception e) {
            log.error("查询待审核详情失败", e);
            throw new BusinessException(ConvPhotoExceptionCode.PENDING_AUDIT_DETAIL_ERROR);
        }
    }

    @Override
    public PendingAuditDetailDto queryPendingAuditDetailByNext(Integer isAsc) {
        try {
            PendingAuditDetailDto detailDto = new PendingAuditDetailDto();

            Long minuteBefore = DateFormatAppUtils.getTimeBeforeMinutes(AppConstant.LOCK_MINUTES);

            // 1. 查询未锁定的下一条记录, 排序, limit
            Map<String, Object> paramMap = new HashedMap();
            paramMap.put("isAsc", isAsc);
            paramMap.put("minuteBefore", minuteBefore);
            ConvPhotoInfo photoInfo = convPhotoInfoMapper.queryNextPendingAuditDetailByCreateTime(paramMap);

            if (photoInfo == null) {
                return null;
            }

            detailDto.setConvId(photoInfo.getConvId());
            detailDto.setMobile(photoInfo.getMobile());
            detailDto.setCreateTime(DateFormatAppUtils.getFormatDate(photoInfo.getCreateTime()));
            detailDto.setContent(photoInfo.getContent());
            detailDto.setLocation(photoInfo.getPlace());
            detailDto.setUserType(photoInfo.getAuditCert());
            // 查询专题名称
            if (StringUtils.isNotBlank(photoInfo.getSubjectId())) {
                ConvSubject subjectEntity = convSubjectMapper.querySubjectDetail(Long.valueOf(photoInfo.getSubjectId()));
                if (subjectEntity != null) {
                    detailDto.setSubjectId(photoInfo.getSubjectId());
                    detailDto.setSubjectName(subjectEntity.getSubjectName());
                }
            }

            List<ConvAttachment> convAttachmentList = convAttachmentMapper.getPhotos(photoInfo.getConvId());

            detailDto.setPhotos(convAttachmentList);


            // 2. 锁定该条记录
            Long lockTime = new Date().getTime();
            convPhotoInfoMapper.lockConvRecord(photoInfo.getConvId(), lockTime);

            return detailDto;
        } catch (Exception e) {
            log.error("查询下一个待审核详情失败", e);
            throw new BusinessException(ConvPhotoExceptionCode.PENDING_NEXT_AUDIT_DETAIL_ERROR);

        }
    }

    @Override
    public AuditConfigDto auditConfig() {
        try {

            // 1. 获取disconf配置项

            AuditConfigDto auditConfigDto = new AuditConfigDto();

            List<ConfigDict> rejectReasonList = ConfigDictUtils.getConfigDictFromProp(ConfigDictUtils.REJECT_TYPE);

            List<ConfigDict> dealTypeList = ConfigDictUtils.getConfigDictFromProp(ConfigDictUtils.DEAL_TYPE);

            auditConfigDto.setRejectReasonList(rejectReasonList);
            auditConfigDto.setDealTypeList(dealTypeList);

            // 2. 调用积分服务 API 获取积分体系内容
            /*List<ConfigDict> integralMattersList = ConfigDictUtils.queryCityDictFromCityService();
            auditConfigDto.setIntegralMattersList(integralMattersList);*/

            return auditConfigDto;

        } catch (Exception e) {
            log.error("获取配置字典项失败", e);
            throw new BusinessException(ConvPhotoExceptionCode.AUDIT_CONFIG_ERROR);
        }
    }

    @Transactional
    @Override
    public boolean addAudit(AddAuditDto addAuditDto, OrgSessionInfo orgSessionInfo) {
        try {
            // 设置id和审核用户信息
            ConvPhotoInfo photoInfo = new ConvPhotoInfo();
            photoInfo.setAuditUserId(orgSessionInfo.getEi());
            photoInfo.setAuditUserName(orgSessionInfo.getEn());
            photoInfo.setConvId(Long.valueOf(addAuditDto.getId()));

            // 审核不通过
            if (AppConstant.CONV_AUDIT_NOT_PASS.equals(addAuditDto.getAuditStatus())) {
                return handleNotPassConvRecord(addAuditDto, photoInfo);
                // 审核通过
            } else {
                boolean needCityIntegral = StringUtils.isNotBlank(addAuditDto.getIntegralMatters());
                return handlePassConvRecord(addAuditDto, photoInfo, needCityIntegral);
            }

        } catch (Exception e) {
            log.error("审核随手拍记录失败", e);
            throw new BusinessException(ConvPhotoExceptionCode.ADD_AUDIT_ERROR);
        }
    }

    /**
     * 处理审核未通过的随手拍记录
     *
     * @param addAuditDto 审核随手拍dto
     * @param photoInfo   随手拍实体
     * @return boolean
     * @author 144637
     */
    private boolean handleNotPassConvRecord(AddAuditDto addAuditDto, ConvPhotoInfo photoInfo) {

        // 1.1 数据入库
        // 审核状态 , 退回原因, 审核人id, 审核人姓名
        photoInfo.setAuditCode(AppConstant.CONV_AUDIT_CODE_NOT_PASS);
        photoInfo.setAudit(AppConstant.CONV_AUDIT_CODE_NOT_PASS_VALUE);
        photoInfo.setReasonCode(addAuditDto.getRejectReason());
        String reason = getReasonFromReasonCode(addAuditDto.getRejectReason(), addAuditDto.getOtherRejectReason());
        photoInfo.setReason(reason);
        photoInfo.setUpdateTime(new Date().getTime());

        int row = convPhotoInfoMapper.auditNotPassAndUpdateConvRecord(photoInfo);

        // 1.2 发送通知
        if (row == 1) {

            handleNotPassMsg(photoInfo, addAuditDto.getMsgContent());

            // 要解锁随手拍记录
            convPhotoInfoMapper.unlockConvRecord(photoInfo.getConvId());

            return true;
        }

        return false;
    }


    /**
     * 处理审核不通过的通知
     *
     * @param photoInfo 随手拍实体
     * @author 144637
     */
    private void handleNotPassMsg(ConvPhotoInfo photoInfo, String msgContent) {

        Long convId = photoInfo.getConvId();

        // 查询userId
        ConvPhotoInfo bean = convPhotoInfoMapper.queryConvDetailById(convId);

        // 设置通知消息体
        String userId = bean.getUserId();
        String code = MsgFormatUtils.getMsgCode(userId);
        String msgUrl = CONV_HOST + AppConstant.MSG_NOT_PASS_URL
                + "?code=" + code + "#/issue?id=" + convId;
        log.info("通知消息url==>{}", msgUrl);
        String buttonTitle = AppConstant.MSG_COMMIT_CONTENT_NOT_PASS_BUTTON;

        MessageAppRequest messageAppRequest = new MessageAppRequest();
        messageAppRequest.setUserId(userId);
        messageAppRequest.setMsgContent(msgContent);
        messageAppRequest.setMsgUrl(msgUrl);
        messageAppRequest.setButtonTitle(buttonTitle);
        messageAppRequest.setFinishFlag(AppConstant.MSG_FINISH_FLAG_NO);

        handleCoverMsg(convId, messageAppRequest);
    }

    /**
     * 获取多个原因
     *
     * @param reasonCodeString  原因编码
     * @param otherRejectReason 其他原因的字符串
     * @return String 原因
     * @author 144637
     */
    private String getReasonFromReasonCode(String reasonCodeString, String otherRejectReason) {
        String reason = "";
        String[] codeStringArray = reasonCodeString.split(",");
        for (int i = 0; i < codeStringArray.length; i++) {
            Integer dictKey = Integer.valueOf(codeStringArray[i]);
            String dictValue = ConfigDictUtils.getDictValueByCode(ConfigDictUtils.REJECT_TYPE, dictKey);
            if (dictKey.equals(AppConstant.OTHER_REJECT_DICT_CODE)) {
                dictValue = otherRejectReason;
            }
            reason += dictValue;
            if (i < (codeStringArray.length - 1)) {
                reason += ",";
            }
        }
        return reason;
    }

    /**
     * 处理审核通过的随手拍记录
     *
     * @param addAuditDto      审核dto
     * @param photoInfo        随手拍实体对象
     * @param needCityIntegral 是否需要添加城市积分
     * @return boolean 是否成功
     * @author 144637
     */
    private boolean handlePassConvRecord(AddAuditDto addAuditDto, ConvPhotoInfo photoInfo, boolean needCityIntegral) {

        // 1. 更新数据库
        // 2. 查询城市积分服务
        // 3. 通知发送

        photoInfo.setAuditCode(AppConstant.CONV_AUDIT_CODE_PASS);
        photoInfo.setAudit(AppConstant.CONV_AUDIT_CODE_PASS_VALUE);
        Integer dealType = addAuditDto.getDealType();
        photoInfo.setTypeCode(dealType);
        photoInfo.setType(ConfigDictUtils.getDictValueByCode(ConfigDictUtils.DEAL_TYPE, dealType));
        long currentTime = new Date().getTime();
        photoInfo.setAuditTime(currentTime);
        photoInfo.setUpdateTime(currentTime);

        /*if (needCityIntegral) {
            // 查询城市积分服务的积分规则项
            Integer itemId = Integer.valueOf(addAuditDto.getIntegralMatters());
            CityItem cityItem = CityIntegralUtils.getCityInteralDetailByItemId(itemId);

            String scoreItem = cityItem.getItem();

            photoInfo.setRewardItem(scoreItem);
            photoInfo.setReward(cityItem.getScore());
        }*/

        // 添加社会警示类型
        if (AppConstant.CONV_PRAISE_BJ.equals(dealType)
                || AppConstant.CONV_PRAISE_SOCIAL_WARN.equals(dealType)) {
            photoInfo.setHandleUserId(photoInfo.getAuditUserId());
            photoInfo.setHandleUserName(photoInfo.getAuditUserName());
            photoInfo.setIsOver(AppConstant.CONV_IS_OVER);
            photoInfo.setShowFlag(AppConstant.SHOW_FLAG_YES);
        } else {
            photoInfo.setHandleUserId("");
            photoInfo.setHandleUserName("");
            photoInfo.setIsOver(AppConstant.CONV_IS_OVER_DEFAULT);
            photoInfo.setHandleStatus(AppConstant.CONV_IS_NOT_OVER);
            // 举报默认不对外公示
            photoInfo.setShowFlag(AppConstant.SHOW_FLAG_NO);
        }

        int row = convPhotoInfoMapper.auditPassAndUpdateConvRecord(photoInfo);

        if (row == 1) {
            // 初始化一条remind表记录
            insertRemindRercord(photoInfo.getConvId());
            // 处理通知
            handlePassMsg(addAuditDto, photoInfo.getConvId(), needCityIntegral);
            // 解锁随手拍记录
            convPhotoInfoMapper.unlockConvRecord(photoInfo.getConvId());
            return true;
        }
        return false;
    }

    /**
     * 插入remind表一条初始化记录
     *
     * @param convId 随手拍记录id
     * @return boolean
     * @author 144637
     */
    private boolean insertRemindRercord(Long convId) {
        ConvPhotoInfo entity = convPhotoInfoMapper.queryConvDetailById(convId);

        ConvRemindRecord convRemindRecord = new ConvRemindRecord();

        convRemindRecord.setConvId(convId);
        convRemindRecord.setConvType(entity.getTypeCode());
        convRemindRecord.setCommentCount(0L);
        convRemindRecord.setHandleRecordCount(0L);
        convRemindRecord.setUserId(entity.getUserId());
        Long currentTime = new Date().getTime();
        convRemindRecord.setCreateTime(currentTime);
        convRemindRecord.setUpdateTime(currentTime);

        int row = convRemindRecordMapper.addRemind(convRemindRecord);
        return row == 1;
    }

    /**
     * 处理审核通过的消息
     *
     * @param addAuditDto      审核dto
     * @param convId           随手拍记录id
     * @param needCityIntegral 是否需要添加城市积分
     * @author 144637
     */
    private void handlePassMsg(AddAuditDto addAuditDto, Long convId, boolean needCityIntegral) {

        Integer dealType = addAuditDto.getDealType();

        ConvPhotoInfo bean = convPhotoInfoMapper.queryConvDetailById(convId);

        String userId = bean.getUserId();

        // 查询实名认证状态
        boolean isCerted = CertficateUtils.getCertApply(userId);

        /*if (needCityIntegral) {
            // 调用积分服务API,增加积分
            boolean success = CityIntegralUtils.addCityIntegral(userId, addAuditDto.getIntegralMatters());

            if (!success) {
                log.error("城市积分服务添加积分失败");
                throw new BusinessException(ConvPhotoExceptionCode.CITY_INTEGRAL_ERROR);
            }
        }*/

        String code = MsgFormatUtils.getMsgCode(userId);
        String buttonTitle = AppConstant.MSG_BUTTON_DETAIL;
        String msgUrl = CONV_HOST;


        if (AppConstant.CONV_REPORT.equals(dealType)) {    // 举报处理通知url
            if (isCerted) {
                msgUrl += AppConstant.MSG_PASS_CERT_REPROT_URL + "?code=" + code + "#/detail-report/" + convId + "?";
            } else {
                msgUrl += AppConstant.MSG_PASS_NOT_CERT_REPROT_URL + "?code=" + code + "#/detail-report/" + convId + "?";
            }
        } else { // 其他类型通知url
            if (isCerted) {
                msgUrl += AppConstant.MSG_PASS_CERT_URL + "?code=" + code + "#/detail-praising/" + convId + "?";

            } else {
                msgUrl += AppConstant.MSG_PASS_NOT_CERT_URL + "?code=" + code + "#/detail-praising/" + convId + "?";
            }
        }
        log.info("通知消息url==>{}", msgUrl);

        MessageAppRequest messageAppRequest = new MessageAppRequest();
        messageAppRequest.setUserId(userId);
        messageAppRequest.setMsgContent(addAuditDto.getMsgContent()); // 通知消息体为前端传递的消息
        messageAppRequest.setMsgUrl(msgUrl);
        messageAppRequest.setButtonTitle(buttonTitle);
        messageAppRequest.setFinishFlag(AppConstant.MSG_FINISH_FLAG_NO);

        handleCoverMsg(convId, messageAppRequest);
    }

    /**
     * 处理消息覆盖
     *
     * @param convId            随手拍记录id
     * @param messageAppRequest 通知入参对象
     * @author 144637
     */
    private void handleCoverMsg(Long convId, MessageAppRequest messageAppRequest) {

        ConvMsgRecord msgRecordEntity = convMsgRecordMapper.selectMsgRecordByConvId(convId);

        // 判断消息记录是否存在
        boolean existsMsgRecord = (msgRecordEntity != null);

        String bizNo;

        if (existsMsgRecord) {
            bizNo = msgRecordEntity.getBizNo();
        } else {
            // 如果不存在记录,随机生成消息 bizNo
            bizNo = UUID.randomUUID().toString();
        }
        // 记录消息内容
        ConvMsgRecord msgRecord = new ConvMsgRecord();
        msgRecord.setUserId(messageAppRequest.getUserId());
        msgRecord.setConvId(convId);
        msgRecord.setBizNo(bizNo);
        msgRecord.setMsgContent(messageAppRequest.getMsgContent());
        long currentTime = new Date().getTime();
        if (!existsMsgRecord) {
            msgRecord.setCreateTime(currentTime);
        }
        if (existsMsgRecord) {
            msgRecord.setMsgRecordId(msgRecordEntity.getMsgRecordId());
        }
        msgRecord.setUpdateTime(currentTime);

        // 添加或删除通知记录
        if (existsMsgRecord) {
            convMsgRecordMapper.updateMsgRecordById(msgRecord);
        } else {
            convMsgRecordMapper.insertMsgRecord(msgRecord);
        }

        // 设置消息bizNo
        messageAppRequest.setBizNo(bizNo);
        // 消息发送
        IMUtils.sendToonMessage(messageAppRequest);
    }

    @Override
    public Page queryReportList(Page page) {
        try {
            // 1.查询状态为举报的随后拍记录, 未锁定的
            // 2.分页,条件查询
            page.setMinuteBefore(DateFormatAppUtils.getTimeBeforeMinutes(AppConstant.LOCK_MINUTES));
            // 查询数据
            List<ConvPhotoInfo> convPhotoInfoList = convPhotoInfoMapper.queryReportList(page);
            // 查询数据条数
            Integer dataTotal = convPhotoInfoMapper.queryReportListCount(page);
            //  参数转换,处理
            List<PendingReportListResultItemDto> resultItmeDtoList = convertToReportResultItemDto(convPhotoInfoList);
            // 返回参数
            if (dataTotal == null) {
                dataTotal = 0;
            }
            page.setResult(resultItmeDtoList);
            page.setDataTotal(dataTotal);
            return page;
        } catch (Exception e) {
            log.error("查询举报列表失败", e);
            throw new BusinessException(ConvPhotoExceptionCode.REPORT_LIST_ERROR);
        }
    }

    @Override
    public ReportDetailDto queryReportById(Long convId, Integer isEdit) {
        try {

            ReportDetailDto detailDto = new ReportDetailDto();

            // 1. 查询随手拍详情
            ConvPhotoInfo photoInfo = convPhotoInfoMapper.queryConvDetailById(convId);

            detailDto.setConvId(photoInfo.getConvId());
            detailDto.setMobile(photoInfo.getMobile());
            detailDto.setCreateTime(DateFormatAppUtils.getFormatDate(photoInfo.getCreateTime()));
            detailDto.setContent(photoInfo.getContent());
            detailDto.setLocation(photoInfo.getPlace());
            detailDto.setUserType(photoInfo.getAuditCert());
            detailDto.setTypeCode(photoInfo.getTypeCode());
            detailDto.setReportStatus(photoInfo.getHandleStatus());
            detailDto.setIsSubmitZfhf(photoInfo.getHandleType());
            detailDto.setShowFlag(photoInfo.getShowFlag());
            // 处理反馈意见
            Integer feedbackDict = photoInfo.getFeedback();
            if (AppConstant.CONV_FEEDBACK_YES.equals(feedbackDict)) {
                detailDto.setUserFeedback(AppConstant.CONV_FEEDBACK_YES_VALUE);
                detailDto.setUserFeedbackTime(DateFormatAppUtils.getFormatDate(photoInfo.getFeedbackTime()));
            } else if (AppConstant.CONV_FEEDBACK_NO.equals(feedbackDict)) {
                detailDto.setUserFeedback(AppConstant.CONV_FEEDBACK_NO_VALUE);
                detailDto.setUserFeedbackTime(DateFormatAppUtils.getFormatDate(photoInfo.getFeedbackTime()));
                detailDto.setUserFeedbackContent(photoInfo.getFeedbackOpinion());
            }

            Integer handleRecordCount = convHandleRecordMapper.queryCountByConvId(convId);

            detailDto.setHandleRecordCount(handleRecordCount);

            // 处理政风行风系统回复消息
            if (AppConstant.HANDLE_MODEL_BJ_WINDOW.equals(photoInfo.getHandleType())) {
                handleZfhfLetterInfo(detailDto, convId);
            }

            // 查询专题名称
            if (StringUtils.isNotBlank(photoInfo.getSubjectId())) {
                ConvSubject subjectEntity = convSubjectMapper.querySubjectDetail(Long.valueOf(photoInfo.getSubjectId()));
                if (subjectEntity != null) {
                    detailDto.setSubjectId(photoInfo.getSubjectId());
                    detailDto.setSubjectName(subjectEntity.getSubjectName());
                }
            }
            // 2. 查询附件信息
            List<ConvAttachment> convAttachmentList = convAttachmentMapper.getPhotos(convId);

            detailDto.setPhotos(convAttachmentList);

            // 3. 锁定该条记录
            Long lockTime = new Date().getTime();

            // 如果是编辑页面,锁定记录
            if (isEdit == 1) {
                convPhotoInfoMapper.lockConvRecord(convId, lockTime);
            }

            return detailDto;
        } catch (Exception e) {
            log.error("查询待审核详情失败", e);
            throw new BusinessException(ConvPhotoExceptionCode.PENDING_AUDIT_DETAIL_ERROR);
        }

    }

    /**
     * 处理首都之窗的信件信息
     *
     * @param detailDto 举报详情dto,
     * @param convId    随手拍记录id
     * @author 144637
     */
    private void handleZfhfLetterInfo(ReportDetailDto detailDto, Long convId) {
        // 1.查询信件回复
        // 2.参数转换, 设置dto
        // TODO 3.信件不受理, 信件无回复, 信件有回复
        List<ZfhfLetterResultDto> zfhfInfo = replyService.queryZfhfReplyByConvId(convId);
        detailDto.setZfhfInfo(zfhfInfo);
    }

    @Override
    public String queryMsgContentBeforeAuditReport(AddReportDto addReportDto) {

        // 查询随手拍记录信息
        Long convId = addReportDto.getId();
        ConvPhotoInfo bean = convPhotoInfoMapper.queryConvDetailById(convId);

        String msgContent = "";
        String convContent = MsgFormatUtils.getConvContent(bean.getContent());
        String convPushTime = MsgFormatUtils.getConvPushTime(bean.getCreateTime());
        String handleStatus = AppConstant.MSG_HANDLE_NOT_OVER;

        // 提交到首都之窗的消息体
        if (AppConstant.HANDLE_MODEL_BJ_WINDOW.equals(addReportDto.getReportType())) {
            //办结时通知消息体
            if (AppConstant.CONV_IS_OVER.equals(addReportDto.getReportStatus())) {
                handleStatus = AppConstant.MSG_HANDLE_OVER;
            }
            String channel = StringUtils.isBlank(addReportDto.getReportChannel()) ?
                    AppConstant.BJ_WINDOW_HANDLE_CHANNEL : addReportDto.getReportChannel();
            String result = StringUtils.isBlank(addReportDto.getReportResult()) ?
                    AppConstant.BJ_WINDOW_HANDLE_RESULT : addReportDto.getReportResult();
            msgContent = String.format(AppConstant.MSG_COMMIT_CONTENT_BJ_WINDOWN,
                    convContent, convPushTime, channel, result, handleStatus);
        } else {
            //办结时通知消息体
            if (AppConstant.CONV_IS_OVER.equals(addReportDto.getReportStatus())) {
                handleStatus = AppConstant.MSG_HANDLE_OVER;
                msgContent = String.format(AppConstant.MSG_COMMIT_CONTENT_IS_OVER,
                        convContent, convPushTime, addReportDto.getReportChannel(), addReportDto.getReportResult(), handleStatus);
            } else {
                msgContent = String.format(AppConstant.MSG_COMMIT_CONTENT_DEAL_NODE,
                        convContent, convPushTime, addReportDto.getReportChannel(), addReportDto.getReportResult(), handleStatus);
            }
        }

        return msgContent;
    }

    @Override
    public List<ResultProblemHandDto> queryProblemHandList(String pageNum, String pageSize) {
        Integer num = Integer.valueOf(pageNum);
        Integer size = Integer.valueOf(pageSize);
        List<ConvPhotoInfo> list = convPhotoInfoMapper.getProblemHandList((num - 1) * size, size);
        List<ResultProblemHandDto> resultProblemHandListDtoList = new ArrayList<>();
        for (ConvPhotoInfo convPhotoInfo : list) {
            try {
                ResultProblemHandDto resultProblemHandListDto = new ResultProblemHandDto();
                resultProblemHandListDto.setId(String.valueOf(convPhotoInfo.getConvId()));
                resultProblemHandListDto.setTitle(convPhotoInfo.getContent());
                int photos = convAttachmentMapper.getPhotosCount(convPhotoInfo.getConvId());
                resultProblemHandListDto.setPhotos(String.valueOf(photos));
                //根据随手拍记录id获取第一张图片
                String photo = convAttachmentMapper.getPhoto(convPhotoInfo.getConvId());
                resultProblemHandListDto.setPhoto(photo);

                // 查询专题名称
                if (StringUtils.isNotBlank(convPhotoInfo.getSubjectId())) {
                    ConvSubject subjectEntity = convSubjectMapper.querySubjectDetail(Long.valueOf(convPhotoInfo.getSubjectId()));
                    if (subjectEntity != null) {
                        resultProblemHandListDto.setSubjectId(convPhotoInfo.getSubjectId());
                        resultProblemHandListDto.setSubjectName(subjectEntity.getSubjectName());
                    }
                }

                resultProblemHandListDtoList.add(resultProblemHandListDto);
            } catch (Exception e) {
                log.error("查询举报列表失败", e);
            }
        }
        return resultProblemHandListDtoList;
    }

    /**
     * 处理审核举报通知 144637
     *
     * @param addReportDto 添加处理举报dto
     * @author 144637
     */
    private void handleAuditReportMsg(AddReportDto addReportDto) {

        Long convId = addReportDto.getId();
        ConvPhotoInfo bean = convPhotoInfoMapper.queryConvDetailById(convId);
        String userId = bean.getUserId();
        //3.发送通知

        //3.1 每个节点处理发送通知

        String msgContent = "";
        String msgUrl = "";
        String code = MsgFormatUtils.getMsgCode(userId);
        String buttonTitle = AppConstant.MSG_BUTTON_DETAIL;

        // 提交到首都之窗
        if (AppConstant.HANDLE_MODEL_BJ_WINDOW.equals(addReportDto.getReportType())) {
            msgUrl = CONV_HOST + AppConstant.MSG_REPORT_BJ_WINDOW_URL
                    + "?code=" + code + "#/detail-report/" + convId + "?";
            if (AppConstant.CONV_IS_OVER.equals(addReportDto.getReportStatus())) {
                buttonTitle = AppConstant.MSG_COMMIT_CONTENT_IS_OVER_BUTTON;
            }
        } else {
            //3.2 办结时发送通知
            if (AppConstant.CONV_IS_OVER.equals(addReportDto.getReportStatus())) {
                msgUrl = CONV_HOST + AppConstant.MSG_REPORT_SERVICE_IS_OVER_URL
                        + "?code=" + code + "#/detail-report/" + convId + "?";
                buttonTitle = AppConstant.MSG_COMMIT_CONTENT_IS_OVER_BUTTON;
            } else {
                msgUrl = CONV_HOST + AppConstant.MSG_REPORT_SERVICE_NOT_OVER_URL
                        + "?code=" + code + "#/detail-report/" + convId + "?";
            }
        }
        log.info("通知消息url==>{}", msgUrl);
        msgContent = addReportDto.getMsgContent();

        MessageAppRequest messageAppRequest = new MessageAppRequest();
        messageAppRequest.setUserId(userId);
        messageAppRequest.setMsgContent(msgContent);
        messageAppRequest.setMsgUrl(msgUrl);
        messageAppRequest.setButtonTitle(buttonTitle);
        messageAppRequest.setFinishFlag(AppConstant.MSG_FINISH_FLAG_NO);

        handleCoverMsg(convId, messageAppRequest);
    }

    @Transactional
    @Override
    public boolean addReport(AddReportDto addReportDto, OrgSessionInfo orgSessionInfo) {
        try {

            //1. 更新随手拍记录表
            ConvPhotoInfo photoInfo = new ConvPhotoInfo();

            Long convId = addReportDto.getId();

            photoInfo.setConvId(convId);
            photoInfo.setIsOver(Integer.valueOf(addReportDto.getReportStatus()));
            photoInfo.setUpdateTime(new Date().getTime());
            photoInfo.setHandleUserId(orgSessionInfo.getEi());
            photoInfo.setHandleUserName(orgSessionInfo.getEn());
            // 查询之前的处理类型是否是提交到首都之窗,如果已经提交到首都之窗,handleType不再更新
            ConvPhotoInfo convPhotoEntity = convPhotoInfoMapper.queryConvDetailById(convId);
            if (!AppConstant.HANDLE_MODEL_BJ_WINDOW.equals(convPhotoEntity.getHandleType())) {
                photoInfo.setHandleType(addReportDto.getReportType());
            }
            photoInfo.setHandleStatus(addReportDto.getReportStatus());
            if (addReportDto.getShowFlag() != null) {
                photoInfo.setShowFlag(addReportDto.getShowFlag());
            }

            int row = convPhotoInfoMapper.auditReportAndUpdate(photoInfo);

            // 如果为提交首都之窗,调用中科软提交信件接口
            if (AppConstant.HANDLE_MODEL_BJ_WINDOW.equals(addReportDto.getReportType())) {

                List<ConvAttachment> attachmentList = convAttachmentMapper.getPhotos(convId);
                String userId = convPhotoEntity.getUserId();
                ConvLetterParam convLetterParam = new ConvLetterParam();
                convLetterParam.setConvId(convId);
                convLetterParam.setLetterTitle(addReportDto.getTitle());
                convLetterParam.setUserId(userId);
                convLetterParam.setLetterContent(convPhotoEntity.getContent());
                convLetterParam.setLetterAttachList(attachmentList);
                // 测试乱码问题
                boolean letterSuccess = letterService.addLetterFromConvphoto(convLetterParam);
                if (!letterSuccess) {
                    throw new BusinessException(ConvPhotoExceptionCode.CONV_ADD_LETTER_FAIL);
                }
            }

            if (row == 1) {
                int recordRow = addHandleRecord(addReportDto, orgSessionInfo);
                if (recordRow == 1) {
                    handleAuditReportMsg(addReportDto);
                    convPhotoInfoMapper.unlockConvRecord(convId);
                    return true;
                }
            }

            return false;
        } catch (Exception e) {
            log.error("审核举报失败", e);
            throw new BusinessException(ConvPhotoExceptionCode.ADD_REPORT_ERROR);
        }
    }

    /**
     * 添加处理记录
     *
     * @param addReportDto   处理举报dto,
     * @param orgSessionInfo 会话信息
     * @return int
     * @author 144637
     */
    private int addHandleRecord(AddReportDto addReportDto, OrgSessionInfo orgSessionInfo) {

        ConvHandleRecord convHandleRecord = new ConvHandleRecord();

        convHandleRecord.setConvId(addReportDto.getId());

        convHandleRecord.setHandlePersonId(orgSessionInfo.getEi());
        convHandleRecord.setHandlePerson(orgSessionInfo.getEn());

        //设置处理方式
        convHandleRecord.setHandleModeId(addReportDto.getReportType());

        String handleModel = "";
        if (AppConstant.HANDLE_MODEL_SERVICE.equals(addReportDto.getReportType())) {
            handleModel = AppConstant.HANDLE_MODEL_SERVICE_VALUE;
        } else if (AppConstant.HANDLE_MODEL_BJ_WINDOW.equals(addReportDto.getReportType())) {
            handleModel = AppConstant.HANDLE_MODEL_BJ_WINDOW_VALUE;
            // 如果提交到首都之窗,但处理途径和处理结果没填写
            if (StringUtils.isBlank(addReportDto.getReportChannel())) {
                addReportDto.setReportChannel(AppConstant.BJ_WINDOW_HANDLE_CHANNEL);
                addReportDto.setReportResult(AppConstant.BJ_WINDOW_HANDLE_RESULT);
            }
        }
        convHandleRecord.setHandleMode(handleModel);


        // 途径
        convHandleRecord.setHandleChannel(addReportDto.getReportChannel());
        // 结果
        convHandleRecord.setHandleResult(addReportDto.getReportResult());

        convHandleRecord.setCreateTime(new Date().getTime());
        convHandleRecord.setUpdateTime(new Date().getTime());

        return convHandleRecordMapper.addHandleRecord(convHandleRecord);
    }

    @Override
    public Page queryPublishedConvList(Page page) {
        try {

            // 1.查询状态为最美北京和社会警示的的已审核过的随手拍记录

            // 2.分页,条件查询

            // 查询数据
            List<ConvPhotoInfo> convPhotoInfoList = convPhotoInfoMapper.queryPublishedConvList(page);

            // 查询数据条数
            Integer dataTotal = convPhotoInfoMapper.queryPublishedConvListCount(page);

            //  参数转换,处理
            List<PublishedConvListResultItemDto> resultItmeDtoList = convertToPublishedConvListResultItem(convPhotoInfoList);

            // 返回参数
            if (dataTotal == null) {
                dataTotal = 0;
            }

            page.setResult(resultItmeDtoList);
            page.setDataTotal(dataTotal);

            return page;
        } catch (Exception e) {
            log.error("查询举报列表失败", e);
            throw new BusinessException(ConvPhotoExceptionCode.REPORT_DONE_LIST_ERROR);
        }
    }

    /**
     * 对象转换
     *
     * @param convPhotoInfoList 随手拍实体list
     * @return List<PublishedConvListResultItemDto>
     * @author 144637
     */
    private List<PublishedConvListResultItemDto> convertToPublishedConvListResultItem(List<ConvPhotoInfo> convPhotoInfoList) {
        List<PublishedConvListResultItemDto> dtoList = new ArrayList<>();
        for (ConvPhotoInfo item : convPhotoInfoList) {
            PublishedConvListResultItemDto dto = new PublishedConvListResultItemDto();
            dto.setConvId(item.getConvId());
            dto.setMobile(item.getMobile());
            dto.setContent(item.getContent());
            dto.setCreateTime(DateFormatAppUtils.getFormatDate(item.getCreateTime()));
            dto.setAuditPassTime(DateFormatAppUtils.getFormatDate(item.getAuditTime())); // 审核时间
            dto.setFollowManage(item.getAuditUserName());
            dto.setUserType(item.getAuditCert());
            dto.setDealWay(MsgFormatUtils.getConvType(item.getTypeCode()));
            // 添加字段 2017-6-23 17:39:04 二期
            Long convId = item.getConvId();
            String firstPhotoUrl = convAttachmentMapper.getPhoto(convId);
            dto.setShowImgUrl(firstPhotoUrl);

            Integer totalImgCount = convAttachmentMapper.getPhotosCount(convId);
            dto.setTotalImg(totalImgCount);

            Integer praiseSum = convPraiseInfoMapper.getPraiseCount(convId);
            dto.setPraiseSum(praiseSum);

            // TODO 确认是否查询待审核的
            Integer commentSum = convCommentMapper.getCommentContByConvId(convId);
            dto.setCommentSum(commentSum);
            // 查询专题名称
            if (StringUtils.isNotBlank(item.getSubjectId())) {
                ConvSubject subjectEntity = convSubjectMapper.querySubjectDetail(Long.valueOf(item.getSubjectId()));
                if (subjectEntity != null) {
                    dto.setSubjectId(item.getSubjectId());
                    dto.setSubjectName(subjectEntity.getSubjectName());
                }
            }


            dtoList.add(dto);
        }

        return dtoList;
    }

    @Override
    public boolean unlockAuditRecord(Long convId) {
        try {
            int row = convPhotoInfoMapper.unlockConvRecord(convId);
            return row == 1;
        } catch (Exception e) {
            log.error("解锁随手拍记录失败", e);
            throw new BusinessException(ConvPhotoExceptionCode.UNLOCK_AUDIT_RECORD_ERROR);
        }
    }


    /**
     * 转换为待审核的详情
     *
     * @param convPhotoInfoList 随手拍实体list
     * @return 待审核的详情dto list
     * @author 144637
     */
    private List<PendingAuditListResultItemDto> convertToResultItemDto(List<ConvPhotoInfo> convPhotoInfoList) {

        List<PendingAuditListResultItemDto> dtoList = new ArrayList<>();
        for (ConvPhotoInfo item : convPhotoInfoList) {
            PendingAuditListResultItemDto dto = new PendingAuditListResultItemDto();
            dto.setConvId(item.getConvId());
            dto.setContent(item.getContent());
            dto.setCreateTime(DateFormatAppUtils.getFormatDate(item.getCreateTime()));
            dto.setMobile(item.getMobile());
            dto.setUserType(item.getAuditCert());
            // 设置图片总数和第一张图片的地址
            Map<String, Object> photoMap = convAttachmentMapper.queryPhotoCountAndFirstPhoto(item.getConvId());
            dto.setShowImgUrl(photoMap.get("fileUrl").toString());
            dto.setTotalImg(Integer.valueOf(photoMap.get("attachNum").toString()));
            // 查询专题名称
            if (StringUtils.isNotBlank(item.getSubjectId())) {
                ConvSubject subjectEntity = convSubjectMapper.querySubjectDetail(Long.valueOf(item.getSubjectId()));
                if (subjectEntity != null) {
                    dto.setSubjectId(item.getSubjectId());
                    dto.setSubjectName(subjectEntity.getSubjectName());
                }
            }
            dtoList.add(dto);
        }

        return dtoList;
    }

    /**
     * 转换为举报列表 dto
     *
     * @param convPhotoInfoList 随手拍实体list
     * @return 举报列表dto
     * @author 144637
     */
    private List<PendingReportListResultItemDto> convertToReportResultItemDto(List<ConvPhotoInfo> convPhotoInfoList) {

        List<PendingReportListResultItemDto> dtoList = new ArrayList<>();
        for (ConvPhotoInfo item : convPhotoInfoList) {
            PendingReportListResultItemDto dto = new PendingReportListResultItemDto();
            dto.setConvId(item.getConvId());
            dto.setContent(item.getContent());
            dto.setCreateTime(DateFormatAppUtils.getFormatDate(item.getCreateTime()));
            dto.setMobile(item.getMobile());
            dto.setFollowManage(item.getHandleUserName());
            String dealDate = "";
            if (StringUtils.isNotBlank(item.getHandleUserName())) {
                dealDate = DateFormatAppUtils.getFormatDate(item.getUpdateTime());
            }
            dto.setDealDate(dealDate);
            dto.setFeedback(item.getFeedback());
            dto.setDealWay(item.getTypeCode());
            dto.setUserType(item.getAuditCert());
            dto.setReportStatus(item.getHandleStatus());
            //判断是否有用户反馈时间
            if (item.getFeedbackTime() != null && item.getFeedbackTime() != 0) {
                dto.setUserFinalTime(DateFormatAppUtils.getFormatDate(item.getFeedbackTime()));
            }
            String firstPhotoUrl = convAttachmentMapper.getPhoto(item.getConvId());
            dto.setShowImgUrl(firstPhotoUrl);
            // 查询专题名称
            if (StringUtils.isNotBlank(item.getSubjectId())) {
                ConvSubject subjectEntity = convSubjectMapper.querySubjectDetail(Long.valueOf(item.getSubjectId()));
                if (subjectEntity != null) {
                    dto.setSubjectId(item.getSubjectId());
                    dto.setSubjectName(subjectEntity.getSubjectName());
                }
            }
            dtoList.add(dto);
        }

        return dtoList;
    }

    @Override
    public PublishedConvDetailDto queryPublishedConvDetailById(Long id) {

        PublishedConvDetailDto detailDto = new PublishedConvDetailDto();

        // 1. 查询随手拍详情
        Long convId = id;
        ConvPhotoInfo photoInfo = convPhotoInfoMapper.queryConvDetailById(id);

        detailDto.setConvId(convId);
        detailDto.setMobile(photoInfo.getMobile());
        detailDto.setContent(photoInfo.getContent());
        detailDto.setCreateTime(DateFormatAppUtils.getFormatDate(photoInfo.getCreateTime()));
        detailDto.setLocation(photoInfo.getPlace());
        detailDto.setAuditPassTime(DateFormatAppUtils.getFormatDate(photoInfo.getAuditTime()));
        detailDto.setAuditor(photoInfo.getAuditUserName());
        detailDto.setShowFlag(photoInfo.getShowFlag()); // 是否对外隐藏（1：隐藏；0：不隐藏）
        detailDto.setUserType(photoInfo.getAuditCert());

        Integer praiseSum = convPraiseInfoMapper.getPraiseCount(convId);
        detailDto.setPraiseSum(praiseSum);

        // TODO 确认是否查询待审核的
        Integer commentSum = convCommentMapper.getCommentContByConvId(convId);
        detailDto.setCommentSum(commentSum);

        detailDto.setPhotos(getPhotos(convId));

        String score = MsgFormatUtils.getConvScoreItem(photoInfo.getRewardItem()) + "，"
                + MsgFormatUtils.getConvScore(photoInfo.getReward().toString());
        detailDto.setScore(score);

        // 查询专题名称
        if (StringUtils.isNotBlank(photoInfo.getSubjectId())) {
            ConvSubject subjectEntity = convSubjectMapper.querySubjectDetail(Long.valueOf(photoInfo.getSubjectId()));
            if (subjectEntity != null) {
                detailDto.setSubjectId(photoInfo.getSubjectId());
                detailDto.setSubjectName(subjectEntity.getSubjectName());
            }
        }
        return detailDto;
    }

    @Override
    public String queryMsgContentBeforeAudit(AddAuditDto addAuditDto) {

        String msgContent;
        Long convId = Long.valueOf(addAuditDto.getId());

        // 查询userId
        ConvPhotoInfo bean = convPhotoInfoMapper.queryConvDetailById(convId);
        String userId = bean.getUserId();

        if (AppConstant.CONV_AUDIT_NOT_PASS.equals(addAuditDto.getAuditStatus())) {
            String reason = getReasonFromReasonCode(addAuditDto.getRejectReason(),
                    addAuditDto.getOtherRejectReason());
            String msgReason = reason.replaceAll(",", "；\n");
            msgContent = String.format(AppConstant.MSG_COMMIT_CONTENT_NOT_PASS,
                    MsgFormatUtils.getConvContent(bean.getContent()), MsgFormatUtils.getConvPushTime(bean.getCreateTime()), msgReason);
        } else {
            /*boolean needCityIntegral = StringUtils.isNotBlank(addAuditDto.getIntegralMatters());*/
            boolean isCerted = CertficateUtils.getCertApply(userId);
            /*if (needCityIntegral) {
                msgContent = getMsgContentOfCityIntegral(addAuditDto, bean, isCerted);
            } else {
                msgContent = getMsgContentOfNoCityIntegral(addAuditDto, bean, isCerted);
            }*/
            msgContent = getMsgContentOfNoCityIntegral(addAuditDto, bean, isCerted);
        }
        return msgContent;
    }

    /**
     * 获取不需要添加城市积分的消息体
     *
     * @param addAuditDto 审核dto对象
     * @param bean        随手拍
     * @param isCerted    是否实名
     * @return string
     * @author 144637
     */
    private String getMsgContentOfNoCityIntegral(AddAuditDto addAuditDto, ConvPhotoInfo bean, boolean isCerted) {
        String msgContent;
        String convContent = MsgFormatUtils.getConvContent(bean.getContent());
        String convPushTime = MsgFormatUtils.getConvPushTime(bean.getCreateTime());
        if (AppConstant.CONV_REPORT.equals(addAuditDto.getDealType())) {      // 举报处理通知
            if (isCerted) {
                msgContent = String.format(AppConstant.MSG_COMMIT_CONTENT_PASS_REPORT_CERT_NO_CITY,
                        convContent, convPushTime);  // 实名认证消息体
            } else {
                msgContent = String.format(AppConstant.MSG_COMMIT_CONTENT_PASS_REPORT_NOT_CERT_NO_CITY,
                        convContent, convPushTime);  // 非实名认证消息体
            }
        } else {
            String convType = MsgFormatUtils.getConvType(addAuditDto.getDealType());
            if (isCerted) {
                msgContent = String.format(AppConstant.MSG_COMMIT_CONTENT_PASS_CERT_NO_CITY, convContent,
                        convPushTime, convType);  // 实名认证消息体
            } else {
                msgContent = String.format(AppConstant.MSG_COMMIT_CONTENT_PASS_NOT_CERT_NO_CITY, convContent,
                        convPushTime, convType); // 非实名认证消息体
            }
        }
        return msgContent;
    }

    /**
     * 获取需要添加城市积分的消息体
     *
     * @param addAuditDto 审核dto对象
     * @param bean        随手拍
     * @param isCerted    是否实名
     * @return string
     * @author 144637
     */
    /*private String getMsgContentOfCityIntegral(AddAuditDto addAuditDto, ConvPhotoInfo bean, boolean isCerted) {
        String msgContent;
        Integer itemId = Integer.valueOf(addAuditDto.getIntegralMatters());
        String convContent = MsgFormatUtils.getConvContent(bean.getContent());
        String convPushTime = MsgFormatUtils.getConvPushTime(bean.getCreateTime());

        // 查询城市积分服务的积分规则项
        CityItem cityItem = CityIntegralUtils.getCityInteralDetailByItemId(itemId);
        String scoreItem = cityItem.getItem();
        String score = cityItem.getScore() + "";
        String scoreItemFormat = MsgFormatUtils.getConvScoreItem(scoreItem);
        String scoreFormat = MsgFormatUtils.getConvScore(score);

        if (AppConstant.CONV_REPORT.equals(addAuditDto.getDealType())) {      // 举报处理通知
            if (isCerted) {
                msgContent = String.format(AppConstant.MSG_COMMIT_CONTENT_PASS_REPORT_CERT,
                        convContent, convPushTime, scoreItemFormat, scoreFormat);  // 实名认证消息体
            } else {
                msgContent = String.format(AppConstant.MSG_COMMIT_CONTENT_PASS_REPORT_NOT_CERT,
                        convContent, convPushTime, scoreItemFormat, scoreFormat);  // 非实名认证消息体
            }
        } else {
            String convType = MsgFormatUtils.getConvType(addAuditDto.getDealType());
            if (isCerted) {
                msgContent = String.format(AppConstant.MSG_COMMIT_CONTENT_PASS_CERT, convContent,
                        convPushTime, convType, scoreItemFormat, scoreFormat);  // 实名认证消息体
            } else {
                msgContent = String.format(AppConstant.MSG_COMMIT_CONTENT_PASS_NOT_CERT, convContent,
                        convPushTime, convType, scoreItemFormat, scoreFormat); // 非实名认证消息体
            }
        }
        return msgContent;
    }*/

    @Override
    public List<SubjectConvPhotoDto> getSubjectConvList(Integer pageNum, Integer pageSize, String subjectId, String userId) {

        try {
            List<ConvPhotoInfo> entityList = convPhotoInfoMapper.getSubjectConvList((pageNum - 1) * pageSize, pageSize, subjectId);
            List<SubjectConvPhotoDto> convPhotoDtoList = convertToSubjectConvDtoList(entityList, userId);
            return convPhotoDtoList;
        } catch (Exception e) {
            log.error("获取专题下的随手拍列表错误", e);
            throw new BusinessException(ConvPhotoExceptionCode.GET_SUBJECT_CONV_LIST_ERROR);
        }
    }

    /**
     * entity --> dto list 专题下的随手拍详情
     *
     * @param entityList 随手拍实体列表
     * @param userId     用户id
     * @return List<SubjectConvDto>
     * @author 144637
     */
    private List<SubjectConvPhotoDto> convertToSubjectConvDtoList(List<ConvPhotoInfo> entityList, String userId) {
        List<SubjectConvPhotoDto> subjectConvDtoList = new ArrayList<>();
        for (ConvPhotoInfo entity : entityList) {
            try {
                SubjectConvPhotoDto convPhotoDto = getSubjectConvInfoDto(userId, entity);
                subjectConvDtoList.add(convPhotoDto);
            } catch (Exception e) {
                log.error("专题随手拍列表错误：" + e);
            }
        }
        return subjectConvDtoList;
    }

    /**
     * 获取随手拍基础字段
     *
     * @param userId 用户id
     * @param entity 随手拍实体
     * @return ResultConvPhotoDto
     * @author 144637
     */
    private ResultConvPhotoDto getConvInfoDto(String userId, ConvPhotoInfo entity) {
        ResultConvPhotoDto convPhotoDto = new ResultConvPhotoDto();
        convPhotoDto.setId(String.valueOf(entity.getConvId()));
        convPhotoDto.setContent(entity.getContent());
        convPhotoDto.setCreateTime(DateFormatAppUtils.formatDateTime(entity.getCreateTime()));
        convPhotoDto.setAuditCode(String.valueOf(entity.getAuditCode()));

        //根据随手拍记录id获取图片列表
        convPhotoDto.setPhotos(getPhotos(entity.getConvId()));

        if (entity.getAuditCode() == 3) {
            //判断为举报类的
            if (entity.getTypeCode() == 2) {
                convPhotoDto.setDealStatus(String.valueOf(entity.getIsOver()));
                convPhotoDto.setFeedback(String.valueOf(entity.getFeedback()));
                convPhotoDto.setConvType(String.valueOf(entity.getTypeCode()));
            }
            //判断为最美北京的，或者社会警示的
            if (entity.getTypeCode() == 1 || entity.getTypeCode() == 3) {
                //根据随手拍记录id，userId判断是否点赞
                convPhotoDto.setPraised(isPraise(entity.getConvId(), userId));

                //根据随手拍记录id获取点赞数量
                convPhotoDto.setPraiseCount(getPraiseCount(entity.getConvId()));

                //根据随手拍记录id获取评论数量
                convPhotoDto.setCommentCount(getCommentCount(entity.getConvId(), Long.valueOf(userId)));

            }
            //是否有新提醒
            Boolean commenting = querCommenting(entity.getConvId());
            convPhotoDto.setCommenting(commenting);
        }

        // 查询专题名称
        if (StringUtils.isNotBlank(entity.getSubjectId())) {
            ConvSubject subjectEntity = convSubjectMapper.querySubjectDetail(Long.valueOf(entity.getSubjectId()));
            if (subjectEntity != null) {
                convPhotoDto.setSubjectId(entity.getSubjectId());
                convPhotoDto.setSubjectName(subjectEntity.getSubjectName());
            }

        }
        return convPhotoDto;
    }

    /**
     * 获取专题下的随手拍列表
     *
     * @param userId 用户id
     * @param entity 随手拍实体
     * @return SubjectConvPhotoDto
     * @author 144637
     */
    private SubjectConvPhotoDto getSubjectConvInfoDto(String userId, ConvPhotoInfo entity) {
        SubjectConvPhotoDto convPhotoDto = new SubjectConvPhotoDto();
        convPhotoDto.setConvId(String.valueOf(entity.getConvId()));
        convPhotoDto.setContent(entity.getContent());
        convPhotoDto.setCreateTime(DateFormatAppUtils.formatDateTime(entity.getCreateTime()));

        //根据随手拍记录id获取第一张图片
        String photo = convAttachmentMapper.getPhoto(entity.getConvId());
        convPhotoDto.setPhoto(photo);

        //根据随手拍记录id获取图片总数
        int photos = convAttachmentMapper.getPhotosCount(entity.getConvId());
        convPhotoDto.setPhotos(String.valueOf(photos));

        if (entity.getAuditCode() == 3) {
            convPhotoDto.setConvType(entity.getTypeCode());
            //判断为最美北京的，或者社会警示的
            if (entity.getTypeCode() == 1 || entity.getTypeCode() == 3) {
                //根据随手拍记录id，userId判断是否点赞
                convPhotoDto.setPraised(isPraise(entity.getConvId(), userId));

                //根据随手拍记录id获取点赞数量
                convPhotoDto.setPraiseCount(getPraiseCount(entity.getConvId()));

                //根据随手拍记录id获取评论数量
                convPhotoDto.setCommentCount(getCommentCount(entity.getConvId(), Long.valueOf(userId)));
            }
        }

        return convPhotoDto;
    }

}

